<template>
  <div class="container">
    <h5>请选择PositionLog的txt文件</h5>
    <div class="upload-section">
      <el-upload
        class="upload-demo"
        :action="`${config.baseURL}/positionLog/upload`"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        accept=".txt"
        :auto-upload="true"
        :limit="1"
        :on-exceed="handleExceed"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
      </el-upload>
    </div>
    
    <div v-if="fileTitle" class="title-section">
      <h3>{{ fileTitle }}</h3>
    </div>

    <!-- 列选择区域 -->
    <div v-if="columns.length" class="columns-section">
      <el-checkbox-group v-model="checkedColumns" @change="handleColumnChange">
        <div class="checkbox-grid">
          <div v-for="(column, index) in columns" :key="column" class="checkbox-item">
            <el-checkbox 
              :value="column"
              :style="{ 
                '--checkbox-color': colors[index % colors.length]
              }"
            >
              {{ column }}
            </el-checkbox>
          </div>
        </div>
      </el-checkbox-group>
    </div>

    <!-- 图表区域 -->
    <div v-if="hasData" class="chart-section">
      <div ref="chartRef" style="width: 100%; height: 600px"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { config } from '../../config'

// 数据相关的响应式变量
const fileTitle = ref('')
const columns = ref([])
const columnData = ref({})
const checkedColumns = ref([])
const hasData = ref(false)
const chartRef = ref(null)
let myChart = null

// 添加文件列表的响应式引用
const fileList = ref([])

// 图表颜色数组
const colors = [
  '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
  '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc', '#d45a59',
  '#35c7bd', '#f3d337', '#5d7092', '#f95c5c', '#6dc8ec',
  '#4d8918', '#d69401', '#b86abc', '#c23531', '#2f4554',
  '#61a0a8', '#749f83'
]

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (!chartRef.value) return

  if (myChart) {
    myChart.dispose()
  }
  myChart = echarts.init(chartRef.value)
}

// 更新图表数据
const updateChart = () => {
  if (!myChart || !hasData.value || !checkedColumns.value.length) return

  const series = checkedColumns.value.map((column, index) => {
    const colorIndex = columns.value.indexOf(column) // 使用列的原始索引获取颜色
    return {
      name: column,
      type: 'line',
      smooth: true,
      symbol: 'none',
      data: columnData.value[column].map((value, i) => [i, value]),
      lineStyle: {
        color: colors[colorIndex % colors.length]
      },
      itemStyle: {
        color: colors[colorIndex % colors.length]
      },
      yAxisIndex: column === 'Faraday_Beam_current(mA)' ? 1 : 0  // 使用B轴还是A轴
    }
  })

  const option = {
    title: {
      text: fileTitle.value,
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = `数据点: ${params[0].dataIndex}<br/>`
        params.forEach(param => {
          result += `${param.seriesName}: ${param.data[1].toFixed(4)}<br/>`
        })
        return result
      }
    },
    legend: {
      type: 'scroll',
      top: 25,
      data: checkedColumns.value,
      textStyle: {
        rich: {}
      }
    },
    grid: {
      left: '3%',
      right: '5%',  // 增加右侧空间以容纳B轴
      bottom: '3%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        type: 'slider',
        start: 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'value',
      name: '数据点',
      nameLocation: 'middle',
      nameGap: 30
    },
    yAxis: [
      {
        type: 'value',
        name: 'A轴',
        nameLocation: 'middle',
        nameGap: 50,
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#333'
          }
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: 'B轴 (mA)',
        nameLocation: 'middle',
        nameGap: 50,
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: colors[columns.value.indexOf('Faraday_Beam_current(mA)') % colors.length]  // 使用对应的颜色
          }
        },
        axisLabel: {
          formatter: '{value} mA'
        }
      }
    ],
    series: series
  }

  // 为每个图例项设置对应的颜色
  checkedColumns.value.forEach((column) => {
    const colorIndex = columns.value.indexOf(column)
    option.legend.textStyle.rich[column] = {
      color: colors[colorIndex % colors.length]
    }
  })

  // 强制重新设置选项
  myChart.setOption(option, true)
}

// 处理列选择变化
const handleColumnChange = () => {
  updateChart()
}

// 处理文件上传成功
const handleUploadSuccess = async (response) => {
  if (!response.code || response.code === 200) {  // 添加响应检查
    fileTitle.value = response.title
    columns.value = response.columns
    columnData.value = response.columnData
    hasData.value = true

    // 设置默认选中的列
    const defaultColumns = ['Head Vel (mm/sec)', 'Faraday_Beam_current(mA)']
    checkedColumns.value = columns.value.filter(col => defaultColumns.includes(col))

    // 等待DOM更新
    await nextTick()
    
    // 重新初始化图表
    await initChart()
    updateChart()
    
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 处理文件上传失败
const handleUploadError = (error) => {
  console.error('Upload failed:', error)
  ElMessage.error('文件上传失败')
}

// 监听窗口大小变化
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
})

// 在 script setup 中添加新的处理函数
const handleBeforeUpload = () => {
  // 重置所有数据
  fileTitle.value = ''
  columns.value = []
  columnData.value = {}
  checkedColumns.value = []
  hasData.value = false
  
  // 清理旧的图表实例
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
  
  return true
}

// 修改 handleExceed 函数
const handleExceed = (files) => {
  fileList.value = []  // 清空文件列表
  const file = files[0]
  if (file) {
    handleBeforeUpload()
    // 手动触发上传
    const formData = new FormData()
    formData.append('file', file)
    // 使用 fetch 手动发送请求
    fetch(`/positionLog/upload`, {
      method: 'POST',
      body: formData
    })
    .then(response => response.json())
    .then(data => {
      handleUploadSuccess(data)
    })
    .catch(error => {
      handleUploadError(error)
    })
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.upload-section {
  flex-shrink: 0;
  margin-bottom: 15px;
}

.title-section {
  flex-shrink: 0;
  margin-bottom: 15px;
}

.columns-section {
  flex-shrink: 0;
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.checkbox-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 10px;
}

.checkbox-item :deep(.el-checkbox) {
  margin-right: 15px;
  margin-bottom: 10px;
}

.checkbox-item :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  border-color: var(--checkbox-color);
  background-color: var(--checkbox-color);
}

.checkbox-item :deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: var(--checkbox-color);
}

.checkbox-item :deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: var(--checkbox-color);
}

.checkbox-item :deep(.el-checkbox__label) {
  color: var(--checkbox-color);
}

.chart-section {
  flex: 1;
  min-height: 0;
}

.chart-section > div {
  height: 100% !important;
}

h1, h2, h3 {
  color: #333;
}

button {
  padding: 8px 16px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #cccccc;
  cursor: not-allowed;
}
</style>